/*
WhirlMon - Whirlpool.net forums thread monitor
Copyright (C) 2012  Lindsay Mathieson

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

/*
 * 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.dyndns.blackpaw.whirlmon;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

/**
 * 
 * @author Lindsay Mathieson
 */

public class Json {

	static final String APIURL = "http://whirlpool.net.au/api/?output=json&key=";

	static public class WhirlpoolException extends Exception {

		/**
		 * 
		 */
		private static final long serialVersionUID = 2805224419601325336L;

		public WhirlpoolException(String msg) {
			super(msg);
		}
	}

	static public class WhirlpoolNullAPIException extends WhirlpoolException {

		/**
		 * 
		 */
		private static final long serialVersionUID = 2805224419601325336L;

		public WhirlpoolNullAPIException() {
			super("Must Enter API Key");
		}
	}

	static public JSONObject getJSON(String apiKey, String cmds)
			throws Exception {
		if (apiKey.trim() == "")
			throw new WhirlpoolNullAPIException();

		String url = APIURL + apiKey + cmds;

		HttpClient httpclient = new DefaultHttpClient();

		// Prepare a request object
		HttpGet httpget = new HttpGet(url);

		// Execute the request
		HttpResponse response;

		String result = null;
		response = httpclient.execute(httpget);

		// Get hold of the response entity
		HttpEntity entity = response.getEntity();
		// If the response does not enclose an entity, there is no need
		// to worry about connection release

		if (entity == null)
			throw new WhirlpoolException("NULL Return from server");

		int code = response.getStatusLine().getStatusCode();
		if (code != 200)
			throw new WhirlpoolException("WhirlPool API: "
					+ response.getStatusLine().getReasonPhrase());

		// A Simple Response Read
		InputStream instream = entity.getContent();
		result = convertStreamToString(instream);

		// Closing the input stream will trigger connection release
		instream.close();

		return new JSONObject(result);
	}

	private static String convertStreamToString(InputStream is)
			throws IOException {
		/*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is),
				8192);
		StringBuilder sb = new StringBuilder();

		String line;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} finally {
			is.close();
		}

		return sb.toString();
	}
}
